package org.nanyuan.forum.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.nanyuan.forum.common.AppResult;
import org.nanyuan.forum.common.ResultCode;
import org.nanyuan.forum.dao.MessageMapper;
import org.nanyuan.forum.exception.ApplicationException;
import org.nanyuan.forum.model.Message;
import org.nanyuan.forum.model.User;
import org.nanyuan.forum.service.IMessageService;
import org.nanyuan.forum.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private IUserService userService;

    @Override
    public void create(Message message) {
        //非空校验
        if (message == null || message.getPostUserId() == null
            || message.getReceiveUserId() == null
            || !StringUtils.hasLength(message.getContent())) {

            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验接收人是否存在
        User user = userService.selectById(message.getReceiveUserId());
        if (user == null || user.getDeleteState() == 1) {
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //设置默认值
        message.setState((byte) 0); //未读状态
        message.setDeleteFlag((byte) 0);
        //设置创建与更新的时间
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        //调用dao
        int row = messageMapper.insertSelective(message);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public Message selectById(Long id) {
        //判断非空
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Message message = messageMapper.selectByPrimaryKey(id);
        //返回结果
        return message;
    }

    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        //非空校验
        if (receiveUserId == null || receiveUserId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //直接调用dao
        Integer count = messageMapper.selectUnreadCount(receiveUserId);
        //正常不可能出现null
        if (count == null) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return count;
    }

    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        //非空校验
        if (receiveUserId == null || receiveUserId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);
        //返回结果
        return messages;
    }

    @Override
    public void updateStateById(Long id, Byte state) {
        //非空校验,state: 0 未读，1 已读，2 已回复（可以定义一个枚举类）
        if (id == null || id <= 0 || state < 0 || state > 2) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造更新的对象
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        Date date = new Date();
        updateMessage.setUpdateTime(date);
        //调用dao
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    @Transactional
    public void reply(Long repliedId, Message message) {
        //非空校验
        if (repliedId == null || repliedId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验repliedId对应的对象的状态
        Message currentMessage = messageMapper.selectByPrimaryKey(repliedId);
        if (currentMessage == null || currentMessage.getDeleteFlag() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //更新状态为已回复
        updateStateById(repliedId, (byte) 2);
        //写入数据库
        create(message);

    }
}
